#!/usr/bin python3
# -*- encoding: utf-8 -*-
"""
@author: 关河九州
@contact: 
@software: PyCharm
@file: handle_mysql
@time: 2022/2/23 14:56
"""
import os

import pymysql
from loguru import logger

from base.base_api import BaseApi
from common.handle_path import CONF_DIR

""" =============== mysql数据库操作封装 =============== """


class HandleMysql:
    def __init__(self, **kwargs):
        # 连接到数据库
        try:
            self.con = pymysql.connect(charset="utf8", **kwargs)
        except Exception as e:
            logger.error(f'数据库连接失败，连接参数：{kwargs}')
            raise e
        else:
            # 创建一个游标
            self.cur = self.con.cursor()

    def get_one(self, sql):
        """
        获取查询到的第一条数据
        :param sql:
        :return:
        """
        self.con.commit()
        # 通过execute方法执行sql语句
        self.cur.execute(sql)  # 返回的是记录条数
        # 获取查询到的返回集中的第一条数据
        return self.cur.fetchone()

    def get_all(self, sql):
        """
        获取SQL语句查询到的所有数据
        :param sql:
        :return:
        """
        self.con.commit()
        self.cur.execute(sql)
        # 获取查询到的返回集中的所有数据
        return self.cur.fetchall()

    def count(self, sql):
        """
        获取SQL语句查询到的数量
        :param sql:
        :return:
        """
        self.con.commit()
        res = self.cur.execute(sql)
        return res

    def close(self):
        # 关闭游标
        self.cur.close()
        # 断开连接
        self.con.close()


if __name__ == '__main__':
    p = os.path.join(CONF_DIR, 'config.yaml')
    a = BaseApi()
    conf = a.get_yaml(p)
    mysql = conf['mysql']
    db = HandleMysql(**mysql)
    x = db.count('SELECT * FROM  futureloan.financeLog WHERE id=44708')
    print(x)
